/**
 * 
 */
package com.jxc.service.impl;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.jxc.dao.BaseDaoI;
import com.jxc.dao.GoodsRepertoryDaoI;
import com.jxc.dao.MemberDaoI;
import com.jxc.dao.RemindWarnDaoI;
import com.jxc.dao.RepertoryDaoI;
import com.jxc.model.po.Goods;
import com.jxc.model.po.RemindWarn;
import com.jxc.model.po.Repertory;
import com.jxc.model.po.User;
import com.jxc.model.vo.DataGrid;
import com.jxc.model.vo.JsonRemindWarn;
import com.jxc.model.vo.VGoodsRepertory;
import com.jxc.model.vo.VMember;
import com.jxc.model.vo.VRemindWarn;
import com.jxc.service.RemindWarnServiceI;
import com.jxc.util.ExceptionUtil;

/**
 * @author Tino
 * 
 */
@Service("remindWarnService")
public class RemindWarnServiceImpl implements RemindWarnServiceI {
	private final static Logger logger = Logger.getLogger(RemindWarnServiceImpl.class);

	@Autowired
	private BaseDaoI baseDao;
	@Autowired
	private BaseDaoI<RemindWarn> remindWarnDao;
	@Autowired
	private BaseDaoI<JsonRemindWarn> jsonRemindWarnDao;
	@Autowired
	private BaseDaoI<Goods> goodsDao;
	@Autowired
	private MemberDaoI memberDao;
	@Autowired
	private RepertoryDaoI repertoryDao;
	@Autowired
	private RemindWarnDaoI threadRemindWarnDao;
	@Autowired
	private GoodsRepertoryDaoI threadGoodsRepertoryDao;
	
	@Override
	public List<VRemindWarn> combobox(VRemindWarn vrw) {
		return this.changeModel(this.find(vrw));
	}

	@Override
	public DataGrid datagrid(VRemindWarn vrw) {
		DataGrid dg = new DataGrid();
		dg.setRows(this.changeModel(this.find(vrw)));
		dg.setTotal(this.total(vrw));
		return dg;
	}

	@Override
	public void delete(String ids) {
		if (ids != null) {
			for (String id : ids.split(",")) {
				if (!id.trim().equals("0")) {
					RemindWarn rw = this.remindWarnDao.get(RemindWarn.class, Long.parseLong(id.trim()));
					if (rw != null) {
						remindWarnDao.delete(rw);
					}
				}
			}
		}
	}

	@Override
	public void save(VRemindWarn vrw) {
		RemindWarn rw = new RemindWarn();
		BeanUtils.copyProperties(vrw, rw);
		if (vrw.getRid() != null) {
			rw.setRepertory(new Repertory(vrw.getRid()));
		}
		if (vrw.getUid() != null) {
			rw.setUser(new User(vrw.getUid()));
		}
		if (vrw.getCuid() != null) {
			rw.setConfirmUser(new User(vrw.getCuid()));
		}
		this.remindWarnDao.save(rw);
	}
	
	private void threadSave(VRemindWarn vrw) {
		RemindWarn rw = new RemindWarn();
		BeanUtils.copyProperties(vrw, rw);
		if (vrw.getRid() != null) {
			rw.setRepertory( (Repertory) baseDao.get(Repertory.class, vrw.getRid()));
		}
		if (vrw.getUid() != null) {
			rw.setUser((User) baseDao.get(User.class,vrw.getUid()));
		}
		if (vrw.getCuid() != null) {
			rw.setConfirmUser((User) baseDao.get(User.class, vrw.getCuid()));
		}
		this.threadRemindWarnDao.save(rw);
	}

	@Override
	public void update(VRemindWarn vrw) {
		RemindWarn rw = remindWarnDao.get(RemindWarn.class, vrw.getId());
		BeanUtils.copyProperties(vrw, rw, new String[] { "id" });
		if (vrw.getRid() != null) {
			rw.setRepertory(new Repertory(vrw.getRid()));
		}
		if (vrw.getUid() != null) {
			rw.setUser(new User(vrw.getUid()));
		}
		if (vrw.getCuid() != null) {
			rw.setConfirmUser(new User(vrw.getCuid()));
		}
		this.remindWarnDao.update(rw);
	}

	private List<VRemindWarn> changeModel(List<RemindWarn> rws) {
		List<VRemindWarn> vrws = new ArrayList<VRemindWarn>();
		if (rws != null && rws.size() > 0) {
			for (RemindWarn rw : rws) {
				VRemindWarn vrw = new VRemindWarn();
				BeanUtils.copyProperties(rw, vrw);
				if (rw.getUser() != null) {
					vrw.setUid(rw.getUser().getId());
					vrw.setUsername(rw.getUser().getUsername());
				}
				if (rw.getConfirmUser() != null) {
					vrw.setCuid(rw.getConfirmUser().getId());
					vrw.setCuname(rw.getConfirmUser().getUsername());
				}
				if (rw.getRepertory() != null) {
					vrw.setRid(rw.getRepertory().getId());
					vrw.setRname(rw.getRepertory().getName());
				}
				vrws.add(vrw);
			}
		}
		return vrws;
	}

	private List<RemindWarn> find(VRemindWarn vrw) {
		String hql = "from RemindWarn t where 1=1 ";
		List<RemindWarn> vrws = new ArrayList<RemindWarn>();
		List<Object> values = new ArrayList<Object>();
		hql = addWhere(vrw, hql, values);

		if (vrw.getSort() != null && vrw.getOrder() != null) {
			hql += " order by " + vrw.getSort() + " " + vrw.getOrder();
		}
		try{
			vrws = remindWarnDao.find(hql, values);			
		}catch(Exception e){
			e.printStackTrace();
		}
		return vrws;
	}

	private Long total(VRemindWarn vrw) {
		String hql = "select count(*) from RemindWarn t where 1=1 ";
		List<Object> values = new ArrayList<Object>();
		hql = addWhere(vrw, hql, values);
		return this.remindWarnDao.count(hql, values);
	}

	private String addWhere(VRemindWarn vrw, String hql, List<Object> values) {
		if (vrw.getId() != null) {
			hql += " and t.id = ? ";
			values.add(vrw.getId());
		}

		if (vrw.getUid() != null&&vrw.getRid()==null) {
			hql += " and t.user.id = ? ";
			values.add(vrw.getUid());
		}else if (vrw.getRid() != null&&vrw.getUid()==null) {
			hql += " and t.repertory.id = ? ";
			values.add(vrw.getRid());
		}else if(vrw.getRid() != null&&vrw.getUid()!=null) {
			hql += " and ( t.repertory.id = ? or t.user.id = ? ) ";
			values.add(vrw.getRid());
			values.add(vrw.getUid());
		}

		if (vrw.getCuid() != null) {
			hql += " and t.confirmUser.id = ? ";
			values.add(vrw.getCuid());
		}

		if (vrw.getBeginDate() != null) {
			hql += " and t.time >= ? ";
			values.add(vrw.getBeginDate());
		}

		if (vrw.getEndDate() != null) {
			hql += " and t.time <= ? ";
			values.add(vrw.getEndDate());
		}

		if (vrw.getIsDone() != null) {
			hql += " and t.isDone = ? ";
			values.add(vrw.getIsDone());
		}
		
		if (vrw.getType() != null) {
			hql += " and t.type = ? ";
			values.add(vrw.getType());
		}

		return hql;
	}

	private String vgrContentCreate(VGoodsRepertory vgr,String addString) {
		String content =("商品");
		StringBuffer sb	= new StringBuffer(" ");
		if(vgr.getGname()!=null){
			sb.append(" 名称为"+vgr.getGname());
		}
		if(vgr.getBname()!=null){
			sb.append(" 品牌为"+vgr.getBname());
		}
		if(vgr.getType()!=null){
			sb.append(" 款号为"+vgr.getType());
		}
		if(vgr.getSize()!=null){
			sb.append(" 尺码为"+vgr.getSize());
		}
		if(vgr.getRname()!=null){
			sb.append(" 在仓库"+vgr.getRname()+addString);
		}
		content+=sb;
		return content;
	}

	/* (non-Javadoc)
	 * @see com.jxc.service.RemindWarnServiceI#portalTotal(com.jxc.model.vo.VRemindWarn)
	 */
	@Override
	public List<Object[]> portalTotal(VRemindWarn param) {
		String hql = "select type,count(*) from RemindWarn t where 1=1 ";
		
		if (param.getUid() != null&&param.getRid()==null) {
			hql += " and t.user.id = "+param.getUid();
		}else if (param.getRid() != null&&param.getUid()==null) {
			hql += " and t.repertory.id = "+param.getRid();
		}else if(param.getRid() != null&&param.getUid()!=null) {
			hql += " and ( t.repertory.id = "+param.getRid()+" or t.user.id = "+param.getUid()+" ) ";
		}

		if (param.getIsDone() != null) {
			hql += " and t.isDone = "+param.getIsDone();
		}
		
		if (param.getType() != null) {
			hql += " and t.type = "+param.getType();
		}		
		hql +=" group by type";
		List<Object[]> list = this.jsonRemindWarnDao.findList(hql);
		return list;
	}
	
	/**
	 * 库存预警
	 * 
	 */
	@Override
	public void goodsRepertoryTask() {
		logger.info("库存提醒预警任务开始执行.");
		try {
			//删除原来的库存预警信息
			VRemindWarn vrwParam = new VRemindWarn();
			List<VRemindWarn> vrws = threadRemindWarnDao.combobox(vrwParam);
			RemindWarn rw = new RemindWarn();
			for (VRemindWarn vrw : vrws){
				if(vrw.getType()!= null&&(vrw.getType()==11||vrw.getType()==12||vrw.getType()==13||vrw.getType()==14)){
					BeanUtils.copyProperties(vrw, rw);
					threadRemindWarnDao.delete(rw);
				}
			}
			//删除原来的库存预警信息结束
			VGoodsRepertory vgr = new VGoodsRepertory();
			List<VGoodsRepertory> vgrs = threadGoodsRepertoryDao.combobox(vgr);
			SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd"); 
			Date today = ft.parse(ft.format(new Date()));
			
			for (VGoodsRepertory vgr1 : vgrs){
				//负库存预警信息
				long quot = 0;
				if(vgr1.getLastSaleDate()!=null){
					Date  lastSaleDate = ft.parse(ft.format(vgr1.getLastSaleDate()));
					quot = today.getTime()-lastSaleDate.getTime();
					quot = quot/ 1000 / 60 / 60 / 24;
				}
				
				if(vgr1.getNum()!=null&&vgr1.getNum()<0){
					String content = vgrContentCreate(vgr1,"库存为负，建议盘点库存！");
					VRemindWarn vrw = new VRemindWarn();
					vrw.setType(11);
					vrw.setTime(new Date());
					vrw.setIsDone(false);
					vrw.setContent(content);
					if(vgr1.getRid()!=null){
						vrw.setRid(vgr1.getRid());
					}
					if(vgr1.getUid()!=null){
						vrw.setUid(vgr1.getUid());
					}
					this.threadSave(vrw);
				}else if(vgr1.getNum()!=null&&vgr1.getNum()==0){
					String content = vgrContentCreate(vgr1,"库存为零，请及时补货！");
					VRemindWarn vrw = new VRemindWarn();
					if(vgr1.getRid()!=null){
						vrw.setRid(vgr1.getRid());
					}
					if(vgr1.getUid()!=null){
						vrw.setUid(vgr1.getUid());
					}
					vrw.setType(12);
					vrw.setTime(new Date());
					vrw.setIsDone(false);
					vrw.setContent(content);
					this.threadSave(vrw);
				}else if(vgr1.getNum()!=null&&vgr1.getNum()<5&&vgr1.getNum()>0){
					String content = vgrContentCreate(vgr1,"库存小于5件，请及时补货！");
					VRemindWarn vrw = new VRemindWarn();
					if(vgr1.getRid()!=null){
						vrw.setRid(vgr1.getRid());
					}
					if(vgr1.getUid()!=null){
						vrw.setUid(vgr1.getUid());
					}
					vrw.setType(13);
					vrw.setTime(new Date());
					vrw.setIsDone(false);
					vrw.setContent(content);
					this.threadSave(vrw);
				}
				if(quot>90){
					String content = vgrContentCreate(vgr1,"已经超过90天没有销售！");
					VRemindWarn vrw = new VRemindWarn();
					if(vgr1.getRid()!=null){
						vrw.setRid(vgr1.getRid());
					}
					if(vgr1.getUid()!=null){
						vrw.setUid(vgr1.getUid());
					}
					vrw.setType(14);
					vrw.setTime(new Date());
					vrw.setIsDone(false);
					vrw.setContent(content);
					this.threadSave(vrw);
				}
			}
	
		} catch (Exception e) {
			e.printStackTrace();
			logger.info(ExceptionUtil.getExceptionMessage(e));
		}
	}

	/**
	 * 会员生日预警
	 * 
	 */
	@Override
	public void memberBirthdayTask() {
		logger.info("会员生日提醒预警任务开始执行.");
		try {
			//删除原有会员生日预警信息
			VRemindWarn vrwParam = new VRemindWarn();
			List<VRemindWarn> vrws = threadRemindWarnDao.combobox(vrwParam);
			RemindWarn rw = new RemindWarn();
			for (VRemindWarn vrw : vrws){
				if(vrw.getType()!= null&&(vrw.getType()==21||vrw.getType()==22||vrw.getType()==33)){
					BeanUtils.copyProperties(vrw, rw);
					threadRemindWarnDao.delete(rw);
				}
			}
			
			//删除原有会员生日预警信息结束
			
			//查询近期生日会员并写入预警表
			VMember vmParam = new VMember();
			List<VMember> vms = memberDao.combobox(vmParam);
			SimpleDateFormat ft = new SimpleDateFormat("MM-dd");
			Date today = ft.parse(ft.format(new Date()));

			for (VMember vm : vms) {
				
				if (vm.getBirthdayA() != null) {
					Date birthday = ft.parse(ft.format(vm.getBirthdayA()));
					long quot = birthday.getTime()-today.getTime();
					quot = quot/ 1000 / 60 / 60 / 24;
					
					if (quot==0) {
						VRemindWarn vrw = new VRemindWarn();
						vrw.setTime(new Date());
						vrw.setIsDone(false);
						vrw.setUid(vm.getUid());
						vrw.setType(21);
						vrw.setContent("会员[姓名：" + vm.getName() + "，编号：" + vm.getSerial() + "]今天生日，请对他/她关怀一下！");
						this.threadSave(vrw);					

					}
					if (quot<=7&&quot>1) {
						VRemindWarn vrw = new VRemindWarn();
						vrw.setTime(new Date());
						vrw.setIsDone(false);
						vrw.setUid(vm.getUid());
						vrw.setType(22);
						vrw.setContent("会员[姓名：" + vm.getName() + "，编号：" + vm.getSerial() + "]一周内生日，请对他/她关怀一下！");
						this.threadSave(vrw);					

					}
					
				}

			}
			//查询近期生日会员并写入预警表结束

		} catch (Exception e) {
			e.printStackTrace();
			logger.info(ExceptionUtil.getExceptionMessage(e));
		}
	}
	
	/**
	 * 会员积分预警
	 * 
	 */
	@Override
	public void memberCreditTask() {
		logger.info("会员积分提醒预警任务开始执行.");
		try {
			//删除原有会员积分预警信息
			VRemindWarn vrwParam = new VRemindWarn();
			List<VRemindWarn> vrws = threadRemindWarnDao.combobox(vrwParam);
			RemindWarn rw = new RemindWarn();
			for (VRemindWarn vrw : vrws){
				if(vrw.getType()!= null&&(vrw.getType()==31||vrw.getType()==32)){
					BeanUtils.copyProperties(vrw, rw);
					threadRemindWarnDao.delete(rw);
				}
			}
			
			//删除原有会员积分预警信息结束
			
			//查询会员积分并写入预警表
			VMember vmParam = new VMember();
			List<VMember> vms = memberDao.combobox(vmParam);
			SimpleDateFormat ft = new SimpleDateFormat("MM-dd");
			Date today = ft.parse(ft.format(new Date()));

			for (VMember vm : vms) {
				if(vm.getPoint()!=null){
					if(vm.getPoint()>6000){
						VRemindWarn vrw = new VRemindWarn();
						vrw.setTime(new Date());
						vrw.setIsDone(false);
						vrw.setUid(vm.getUid());
						vrw.setType(32);
						vrw.setContent("会员[姓名：" + vm.getName() + "，编号：" + vm.getSerial() + "]积分已达到3000！");
						this.threadSave(vrw);	
					}
					if(vm.getPoint()<6000&&vm.getPoint()>3000){
						VRemindWarn vrw = new VRemindWarn();
						vrw.setTime(new Date());
						vrw.setIsDone(false);
						vrw.setUid(vm.getUid());
						vrw.setType(31);
						vrw.setContent("会员[姓名：" + vm.getName() + "，编号：" + vm.getSerial() + "]积分已达到600！");
						this.threadSave(vrw);	
					}
								
				}

			}
			//查询会员积分并写入预警表结束
		} catch (Exception e) {
			e.printStackTrace();
			logger.info(ExceptionUtil.getExceptionMessage(e));
		}
	}
}
